package com.github.mmin18.widget;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.RenderEffect;
import android.graphics.RenderNode;
import android.os.Build;
import android.view.View;

public class AndroidXBlurImpl implements BlurImpl {
	private RenderNode renderNode;
	private float radius;

	@Override
	public boolean prepare(View view, Bitmap buffer, float radius) {
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
			return false;
		}
		this.radius = radius;
		if (renderNode == null) {
			renderNode = new RenderNode("blur");
		}
		return true;
	}

	@Override
	public void release() {
		if (renderNode != null) {
			renderNode.discardDisplayList();
		}
	}

	@Override
	public void blur(Bitmap input, Bitmap output) {
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
			return;
		}

		Canvas canvas = new Canvas(output);
		renderNode.setPosition(0, 0, input.getWidth(), input.getHeight());
		
		// 创建模糊效果
		RenderEffect blurEffect = RenderEffect.createBlurEffect(
			radius, radius, android.graphics.Shader.TileMode.CLAMP);
		renderNode.setRenderEffect(blurEffect);

		// 绘制到RenderNode
		Canvas nodeCanvas = renderNode.beginRecording();
		nodeCanvas.drawBitmap(input, 0, 0, null);
		renderNode.endRecording();

		// 将RenderNode绘制到输出Bitmap
		canvas.drawRenderNode(renderNode);
	}

	// android:debuggable="true" in AndroidManifest.xml (auto set by build tool)
	static Boolean DEBUG = null;

	static boolean isDebug(Context ctx) {
		if (DEBUG == null && ctx != null) {
			DEBUG = (ctx.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
		}
		return DEBUG == Boolean.TRUE;
	}
}
